package com.example.goodog.activities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.goodog.BasicDogInfo;
import com.example.goodog.ExpandAnimation;
import com.example.goodog.GetCalendarResponse;
import com.example.goodog.R;
import com.example.goodog.RawTimeItem;
import com.example.goodog.Utils;
import com.example.goodog.adapters.TimeAdapter;
import com.example.goodog.items.TimeItem;
import com.google.gson.Gson;

public class ParkCalendarActivity extends Activity {

	private String TAG = " GetAppointmentsTask";
	private Context context = this;
	private ArrayList<TimeItem> TimeList;
	private ListView listView;
	private TimeAdapter adapter;
	private long ParkID;
	
	private final String NAMESPACE = "http://GooDog_Results.org/";
	private final String URL = "http://goodog.zapto.org/WebService1.asmx";
	private final String METHOD_NAME = "GetAppointments";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_park_calendar);
		listView = (ListView) findViewById(R.id.listView_calendar);
		
		
		ParkID = getIntent().getLongExtra("ParkID", 0);
		
		Date now = new Date();
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		if(calendar.get(Calendar.MINUTE)>30)
		{
			calendar.set(Calendar.MINUTE, 30);
		}
		else
		{
			calendar.set(Calendar.MINUTE, 0);
		}
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		TimeList = new ArrayList<TimeItem>();
		for(int i = 0 ; i< 2*3*24; i++)
		{
			TimeList.add(new TimeItem(Utils.DateToString(calendar.getTime(), "dd/MM/yy HH:mm")));
			calendar.add(Calendar.MINUTE, 30);
		}
		if(adapter == null)
		{
			adapter = new TimeAdapter(context,TimeList, ParkID);
			adapter.setNotifyOnChange(true);
		}
		listView.setAdapter(adapter);
		SetToolBarAnimationOnClick(listView);
			
		GetAppointmentsTask task = new GetAppointmentsTask();
		
		//Call execute 
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
			task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		else
			task.execute();
		
	}
	
	private void UpdateTimRecordInList(RawTimeItem item, ArrayList<BasicDogInfo> Dogs)
	{
		Log.i(TAG, "UpdateTimRecordInList date: "+item.date);
		TimeItem ti = new TimeItem(item.date); 
		ti.female = item.female;
		ti.male = item.male;
		
		for (long id : item.DogIDs) {
			BasicDogInfo bdi = new BasicDogInfo();
			bdi.ID = id;
			int InsexInDB = Dogs.indexOf(bdi);
			Log.i(TAG, "UpdateTimRecordInList InsexInDB: "+InsexInDB);
			ti.Images.add(Dogs.get(InsexInDB).Image);
		}
		
		int index = TimeList.indexOf(ti);
		Log.i(TAG, "UpdateTimRecordInList index: "+index);
		if( index >=0 )
		{
			TimeList.set(index, ti);
		}
	}
	
	
	public class GetAppointmentsTask extends AsyncTask<Void, Void, Boolean> {
		
		GetCalendarResponse gcr ;
		
		@Override
		protected Boolean doInBackground(Void... params) {

			Log.i(TAG, "before GetAppointments");
			String CalendarResponse = GetAppointments();
			Log.i(TAG, "before GetAppointments");
			Log.i(TAG, "data: "+CalendarResponse);
			if(!CalendarResponse.equals("BAD"))
			{
				Gson gson = new Gson(); 
				Log.i(TAG, "before fromJson");
				gcr = gson.fromJson(CalendarResponse, GetCalendarResponse.class);
				Log.i(TAG, "after fromJson");
				return true;
			}
			return false;
			
		}

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
		
		@Override
		protected void onPostExecute(Boolean b) {
			if(b && gcr != null)
			{
				for (RawTimeItem time : gcr.List) {
					Log.i(TAG, "before UpdateTimRecordInList. time: "+time.date);
					UpdateTimRecordInList(time,gcr.Dogs);
					Log.i(TAG, "after UpdateTimRecordInList");
				}
				adapter.notifyDataSetChanged();
			}
		}
		
		
	}
	
	private String GetAppointments() {
	    //Create request
	    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
	    
	    request.addProperty("ParkID",ParkID);
	    
	    //Create envelope
	    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
	            SoapEnvelope.VER11);
	    envelope.dotNet = true;
	    //Set output SOAP object
	    envelope.setOutputSoapObject(request);
	    //Create HTTP call object
	    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
	 
	    try 
	    {	     
	        androidHttpTransport.call(NAMESPACE+METHOD_NAME, envelope);

            // Get the response
            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
            // Assign it to static variable
            return response.toString(); 
            
	    } 
	    catch (Exception e) 
	    {
	        e.printStackTrace();
	    }
	    return "BAD"; 
	}
	
	
	public void SetToolBarAnimationOnClick(ListView listView) {
		// Creating an item click listener, to open/close our toolbar for each item
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {

				View toolbar = view.findViewById(R.id.toolbar);

				// Creating the expand animation for the item
				ExpandAnimation expandAni = new ExpandAnimation(toolbar, 500);

				// Start the animation on the toolbar
				toolbar.startAnimation(expandAni);
			}
		});
	}

	
}
